#include <string.h>
#include <unistd.h>

#include "addr_ntop.h"
#include "log.h"

const char* basename(const char *name)
{
	const char *cp = strrchr(name, '/');
	if (cp)
		return cp + 1;
	return name;
}

ssize_t writen(int fd, const void *vptr, size_t n)
{
	size_t nleft;
	ssize_t nwritten;
	const char *ptr;

	ptr = vptr;
	nleft = n;
	while (nleft > 0) {
		if ((nwritten = write(fd, ptr, nleft)) <= 0) {
			if (nwritten < 0 && errno == EINTR)
				nwritten = 0;
			else
				return -1;
		}

		nleft -= nwritten;
		ptr += nwritten;
	}

	return n;
}

void log_connect_info(int csock)
{
	char sockname[SOCKADDR_NTOP_BUFLEN];
	char peername[SOCKADDR_NTOP_BUFLEN];

	LOG(LOG_NOTICE, "got a connection: %s,%s",
			sockname_ntop(csock, sockname, sizeof(sockname)),
			peername_ntop(csock, peername, sizeof(peername)));
}

void log_listen_socket_info(int lsock)
{
	char buf[SOCKADDR_NTOP_BUFLEN];

	LOG(LOG_NOTICE, "listen socket init OK, listen on: %s",
			sockname_ntop(lsock, buf, sizeof(buf)));
}
